<template>
  <div>
    <div id="container" style="width: 100%;height: 500px"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import * as echarts from 'echarts';

let myChart = null;
let data = [];
let now = new Date(1997, 9, 3);
let oneDay = 24 * 3600 * 1000;
let value = Math.random() * 1000;

function randomData() {
  now = new Date(+now + oneDay);
  value = value + Math.random() * 21 - 10;
  return {
    name: now.toString(),
    value: [
      [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
      Math.round(value)
    ]
  };
}

for (var i = 0; i < 1000; i++) {
  data.push(randomData());
}

const initChart = () => {
  const chartDom = document.getElementById('container');
  myChart = echarts.init(chartDom);
  const option = {
    title: {
      text: '数据可视化'
    },
    grid: {
      left: 50, // 左内边距
      right: 20 // 右内边距
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        params = params[0];
        var date = new Date(params.name);
        return (
          date.getDate() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getFullYear() +
          ' : ' +
          params.value[1]
        );
      },
      axisPointer: {
        animation: false
      }
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed' // 虚线样式
        }
      }
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, '100%'],
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed' // 虚线样式
        }
      }
    },
    series: [
      {
        name: 'Fake Data',
        type: 'line',
        showSymbol: false,
        data: data
      }
    ]
  };

  myChart.setOption(option);

  setInterval(function () {
    for (var i = 0; i < 5; i++) {
      data.shift();
      data.push(randomData());
    }
    myChart.setOption({
      series: [
        {
          data: data
        }
      ]
    });
  }, 100);
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', myChart.resize);
});
</script>

<style lang="scss" scoped>
</style>
